package com.cqhz.quwan.ui.activity

import android.content.Intent
import android.graphics.Color
import android.graphics.Paint
import android.support.v7.app.AlertDialog
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.EditorInfo
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.StringUtils.isEmpty
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.common.KeyContract.Companion.EXCHANGE_MONEY_FOR_SALE_SWITCH
import com.cqhz.quwan.common.KeyContract.Companion.PRODUCT_DISCOUNT_RATE
import com.cqhz.quwan.model.*
import com.cqhz.quwan.mvp.mall.ProductDetailContract
import com.cqhz.quwan.mvp.mall.ProductDetailPresenter
import com.cqhz.quwan.mvp.mine.AlipayContract
import com.cqhz.quwan.mvp.mine.AlipayPresenter
import com.cqhz.quwan.service.API
import com.cqhz.quwan.ui.base.GoBackActivity
import com.cqhz.quwan.ui.base.WebViewActivity
import com.cqhz.quwan.ui.login.LoginActivity
import com.cqhz.quwan.ui.mine.AddressActivity
import com.cqhz.quwan.ui.mine.LotteryDrawActivity
import com.cqhz.quwan.ui.widget.AttributeButton
import com.cqhz.quwan.ui.widget.flowlayout.TagAdapter
import com.cqhz.quwan.ui.widget.flowlayout.TagFlowLayout
import com.cqhz.quwan.util.formatMoney
import com.cqhz.quwan.util.setLoadImage
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.android.synthetic.main.activity_product_detail.*
import me.militch.quickcore.core.HasDaggerInject
import javax.inject.Inject


/**
 * 商品详情
 * Created by Guojing on 2018/9/11.
 */
class ProductDetailActivity : GoBackActivity(), AlipayContract.View, ProductDetailContract.View, HasDaggerInject<ActivityInject> {

    @Inject
    lateinit var productDetailPresenter: ProductDetailPresenter
    @Inject
    lateinit var alipayPresenter: AlipayPresenter
    private lateinit var wxApi: IWXAPI
    private var loginBean: LoginBean? = null
    private var userInfoBean: UserInfoBean? = null
    private var productDetailBean: ProductDetailBean? = null
    private var productExchangeRate: Double = 0.00
    private var productId: String? = null
    private var type: String = "1"// 交易类型 1：兑换实物 2：代卖
    private var exchangeMethod: String = "0"// 兑换方式 0-支付宝；1-微信（代卖）
    private var productNumber: Int = 1
    private var diamonds: Double = 0.00
    private var exchangeRate: Double = 0.00

    override fun layout(): Int {
        return R.layout.activity_product_detail
    }

    override fun titleBarText(): String? {
        return "商城"
    }

    override fun inject(t: ActivityInject?) {
        t?.inject(this)
    }

    override fun initView() {
        productDetailPresenter.attachView(this)
        alipayPresenter.attachView(this)
        loginBean = APP.get()!!.loginInfo!!

        // 获取数据
        productId = intent.getStringExtra("productId")

        // 加减
        action_minus.setOnClickListener {
            if (et_product_number.text.toString().toInt() > 1) productNumber--
            et_product_number.setText(productNumber.toString())
            setDataChange()
        }
        action_add.setOnClickListener {
            if (diamonds > productNumber * exchangeRate) productNumber++
            et_product_number.setText(productNumber.toString())
            setDataChange()
        }
        et_product_number.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                try {
                    var value = s?.toString()?.toInt() ?: 0
                    productNumber = s?.toString()?.toInt() ?: 0
                    if (value == 0) {
                        productNumber = 1
                        et_product_number.setText("10")
                    }
                } catch (e: NumberFormatException) {
                    productNumber = 1
                }
                setDataChange()
            }
        })
        et_product_number.setOnEditorActionListener { view: View?, i: Int?, event: KeyEvent? ->
            when (i) {
                EditorInfo.IME_ACTION_DONE -> {
                    et_product_number.clearFocus()
                    KeyboardUtils.hideSoftInput(this)
                }
            }
            false
        }
        // 兑换实物
        action_change_goods.setOnClickListener {
            type = "1"
            exchangeMethod = ""
            setExchangeStyle(true)
        }
        // 代卖换钱
        action_change_money.setOnClickListener {
            type = "2"
            setExchangeStyle(false)
        }
        // 支付宝
        action_select_alipay.setOnClickListener {
            exchangeMethod = "0"
            action_select_alipay.setImageResource(R.drawable.mall_alipay_s)
            action_select_wechat.setImageResource(R.drawable.mall_wechat)
        }
        // 微信
        action_select_wechat.setOnClickListener {
            exchangeMethod = "1"
            action_select_alipay.setImageResource(R.drawable.mall_alipay)
            action_select_wechat.setImageResource(R.drawable.mall_wechat_s)
        }
        // 编辑地址
        action_goto_address.setOnClickListener { startActivity(Intent(this, AddressActivity::class.java)) }
        // 买卖服务协议
        action_goto_rule1.setOnClickListener {
            val intent = Intent(this, WebViewActivity::class.java)
            intent.putExtra(KeyContract.Title, "买卖服务协议")
            val url = API.saleAgreement1
            intent.putExtra(KeyContract.Url, url)
            startActivity(intent)
        }
        // 商品代卖代收协议
        action_goto_rule2.setOnClickListener {
            val intent = Intent(this, WebViewActivity::class.java)
            intent.putExtra(KeyContract.Title, "商品代卖代收协议")
            val url = API.saleAgreement2
            intent.putExtra(KeyContract.Url, url)
            startActivity(intent)
        }
        // 绑定微信
        wxApi = WXAPIFactory.createWXAPI(this, KeyContract.WEICHAT_APP_ID, false)
        wxApi.registerApp(KeyContract.WEICHAT_APP_ID)
        // 确定
        action_confirm.setOnClickListener {
            if (diamonds < exchangeRate) {
                showToast("钻石余额不足")
                return@setOnClickListener
            }
            if (type == "1" && (productDetailBean == null || productDetailBean!!.addressInfo == null)) {
                showToast("请填写收货地址")
                return@setOnClickListener
            }
            // 在其选择代卖换钱时，判断其是否绑定支付宝或微信
            when {
                type == "2" && exchangeMethod == "0" && userInfoBean!!.alipayBind != "1" -> {
                    alipayPresenter.auth4alipay()// 绑定支付宝
                    return@setOnClickListener
                }
                type == "2" && exchangeMethod == "1" && userInfoBean!!.wechatBind != "1" -> {
                    // 绑定微信
                    if (wxApi.isWXAppInstalled) {
                        // send oauth request
                        val req = SendAuth.Req()
                        req.scope = "snsapi_userinfo"
                        req.state = "wechat_sdk_auth"
                        wxApi.sendReq(req)
                        // todo 调不起微信，需要前往公众平台修改签名
                    } else {
                        showToast("您还未安装微信")
                    }
                    return@setOnClickListener
                }
                type == "2" && productExchangeRate == 0.00 -> {
                    showToast("回收汇率出错")
                    return@setOnClickListener
                }
                type == "2" -> {
                    AlertDialog.Builder(this)
                            .setTitle("代卖换钱")
                            .setMessage("预计回收" + (exchangeRate * productExchangeRate).toString().formatMoney() + "元")
                            .setNegativeButton("取消") { _, _ -> }
                            .setPositiveButton("提交") { _, _ ->
                                productDetailPresenter.addProductOrder(loginBean!!.userId!!, productId!!, productNumber.toString(), type, exchangeMethod)
                            }.create().show()
                    return@setOnClickListener
                }
            }
            productDetailPresenter.addProductOrder(loginBean!!.userId!!, productId!!, productNumber.toString(), type, exchangeMethod)
        }

        refresh()
    }

    private fun setDataChange() {
        var payAount = productDetailBean!!.productInfo.exchangeRate.toDouble() * productNumber
        tv_diamonds.text = (payAount.toString()).formatMoney() + "钻石"// 消耗钻石
    }

    /**
     * 设置兑换显示样式
     * @param isGoods 是否为实物
     */
    private fun setExchangeStyle(isGoods: Boolean) {
        line_start.visibility = if (isGoods) View.GONE else View.VISIBLE
        line_end.visibility = if (isGoods) View.GONE else View.VISIBLE
        ll_select_payment_method.visibility = if (isGoods) View.GONE else View.VISIBLE
        ll_rule.visibility = if (isGoods) View.GONE else View.VISIBLE
        action_goto_address.visibility = if (isGoods) View.VISIBLE else View.GONE
        action_change_goods.setTextColor(Color.parseColor(if (isGoods) "#d60000" else "#333333"))
        action_change_money.setTextColor(Color.parseColor(if (isGoods) "#333333" else "#d60000"))
        action_change_goods.setBackgroundResource(if (isGoods) R.drawable.sp_stroke_red_x5 else R.drawable.sp_stroke_gray_x5)
        action_change_money.setBackgroundResource(if (isGoods) R.drawable.sp_stroke_gray_x5 else R.drawable.sp_stroke_red_x5)
    }

    override fun showUserInfo(userInfoBean: UserInfoBean) {
        this.userInfoBean = userInfoBean
    }

    override fun setSystemConfig(configKey: String, data: SystemConfigBean) {
        when (configKey) {
            PRODUCT_DISCOUNT_RATE -> {
                productExchangeRate = data.cval.toDouble()
            }
            EXCHANGE_MONEY_FOR_SALE_SWITCH -> {
                action_change_money.visibility = if (data.cval == "1") View.VISIBLE else View.GONE
            }
            else -> {
            }
        }
    }

    override fun showProductDetail(productDetailBean: ProductDetailBean) {
        this.productDetailBean = productDetailBean
        diamonds = productDetailBean.userInfo.diamonds.toDouble()
        exchangeRate = productDetailBean.productInfo.exchangeRate.toDouble()

        iv_product.setLoadImage(context(), productDetailBean.productInfo.imgUrl, R.drawable.mall_img_default)// 商品图片
        tv_product_name.text = productDetailBean.productInfo.model// 商品名称
        tv_price_money.text = "￥" + productDetailBean.productInfo.price.formatMoney()// 等值市价
        tv_price_money.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG // 中划线
        tv_price_money.paint.isAntiAlias = true// 抗锯齿
        tv_price_diamonds.text = productDetailBean.productInfo.exchangeRate.formatMoney() + "钻石"// 等值钻石
        tv_diamonds.text = productDetailBean.productInfo.exchangeRate.formatMoney() + "钻石"// 消耗钻石

        // 颜色
        val colors = productDetailBean.productInfo.color.split(",")
        var colorsAdapter = object : TagAdapter<String>(colors) {
            override fun getView(parent: TagFlowLayout, position: Int, t: Any): View {
                val attributeButton = LayoutInflater.from(context()).inflate(R.layout.layout_attribute_button, parent, false) as AttributeButton
                attributeButton.setText(colors[position])
                attributeButton.isEnabled = true
                attributeButton.isSelected = true
                return attributeButton
            }
        }
        tfl_product_attribute.adapter = colorsAdapter

        tv_type.text = productDetailBean.productInfo.version// 套餐类型
        et_product_number.setText(productNumber.toString())

        // 设置地址信息
        if (productDetailBean.addressInfo != null && !isEmpty(productDetailBean.addressInfo.id)) {
            tv_name_and_phone.visibility = View.VISIBLE
            tv_address.visibility = View.VISIBLE
            tv_address_add.visibility = View.GONE
            tv_name_and_phone.text = productDetailBean.addressInfo.receiver_name + " " + productDetailBean.addressInfo.phone_number
            tv_address.text = productDetailBean.addressInfo.province + productDetailBean.addressInfo.city + productDetailBean.addressInfo.county + productDetailBean.addressInfo.detail_address
        } else {
            tv_name_and_phone.visibility = View.GONE
            tv_address.visibility = View.GONE
            tv_address_add.visibility = View.VISIBLE
        }
    }

    override fun showSuccess(commonResultBean: CommonResultBean) {
        if (commonResultBean.type == "1") {
            startActivity(Intent(this, LotteryDrawActivity::class.java).putExtra("orderId", commonResultBean.id))
        }
        finish()
    }

    override fun alipayAuthCallBack(authData: AlipayAuthData) {
        productDetailPresenter.bindAlipay(APP.get()!!.loginInfo!!.userId!!, authData)
    }

    override fun refresh() {
        if (loginBean != null) {
            productDetailPresenter.getUserInfo(loginBean!!.userId!!)
            productDetailPresenter.getProductDetail(loginBean!!.userId!!, productId!!)
            productDetailPresenter.getSystemConfig(PRODUCT_DISCOUNT_RATE)
            productDetailPresenter.getSystemConfig(EXCHANGE_MONEY_FOR_SALE_SWITCH)
        } else {
            startActivity(Intent(this, LoginActivity::class.java))
        }
    }

    override fun onResume() {
        super.onResume()
        refresh()
    }

    override fun onDestroy() {
        productDetailPresenter.detachView()
        alipayPresenter.detachView()
        super.onDestroy()
    }
}
